$(function(){
   obj.init();
});
var obj;
obj = new function () {
    'use strict';
    return {
        params: {
            id: null,
            ue: null,
            ueOption: {},
            toolbarConfig: [],
            markerId: null,
            release: false,
            typeId: null,
            learnstages: null
        },
        dom: {
            typeDom: null,
            columnDom: null,
            markerDom: null,
            stagesDom: null,
            coverUrlDom: null,
        },
        init: function () {
            this.params.id = xhTool.getQuery('id');
            this.form = new xhForm($('#form_article'));
            this.dom.typeDom = $('#articletype');
            this.dom.columnDom = $('#columns');
            this.dom.markerDom = $('#marker');
            this.dom.stagesDom = $(':checkbox[name*=learnstages]');
            this.dom.coverUrlDom = $('#coverurl');
            this.params.ueOption = {
                autoHeightEnabled: false,
                textarea: 'contents',
                imageScaleEnabled: false,
                dropFileEnabled: true,
                initialFrameHeight: 300
            };
            this.params.toolbarConfig = {
                '1': [
                    'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat',
                    '| insertorderedlist insertunorderedlist | selectall cleardoc paragraph' ,
                    '| justifyleft justifycenter justifyright ',
                    '| image',
                    '| horizontal preview ',
                    '| formula',
                    '| formula1 formula2 formula3 formula4 formula5 formula6 formula7 formula8 formula9 formula10 formula11 formula12 formula13 formula14'
                ],
                '2': [
                    'source | undo redo ',
                    '| selectall cleardoc' ,
                    '| image',
                    '| formula',
                    '| formula1 formula2 formula3 formula4 formula5 formula6 formula7 formula8 formula9 formula10 formula11 formula12 formula13 formula14'
                ]
            };
            // this.params.toolbarConfig = [
            //     ['fullscreen', 'source', '|', 'undo', 'redo', '|',
            //         'directionalityltr', 'directionalityrtl', 'indent', '|',
            //         'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', '|',
            //         'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            //         'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            //         'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', 'insertframe', '|',
            //         'customstyle', 'paragraph', 'fontfamily', 'fontsize', 'insertcode'],
            //     ['removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|',
            //         'link', 'unlink', 'anchor', '|', 'simpleupload', 'insertimage', 'emotion', 'pagebreak', 'template', 'background', '|',
            //         'horizontal', 'date', 'time', 'spechars', '|', 'print', 'preview', 'searchreplace', 'drafts', 'help']
            // ];
            this.listener();
        },
        listener: function () {
            var $this = this;
            // 实例化编辑器
            if ($this.params.id) {
                $.post(baseUrl + 'Read/getArticleInfo', {id: $this.params.id}, function (info) {
                    $this.form.fill(info);
                    $this.params.markerId = info.marker;
                    $this.params.learnstages = info.learnstages;//编辑时添加学段,防止与联动混淆
                    $this.dom.columnDom.trigger('change');
                    // $this.funObj().createUEditor();
                    $this.funObj().createUMEditor($this.dom.typeDom.val());
                    if (info.releasestatus == 1) {
                        $this.params.release = true;
                        $('#save').fadeOut();
                        $('#title').attr('readonly', true);
                        $this.dom.columnDom.add($this.dom.markerDom).add($this.dom.typeDom).prop("disabled", true);
                    }
                    $this.params.learnstages = null//学段置空，不影响联动
                }, 'json');
            } else {
                // $this.funObj().createUEditor();
                $this.funObj().createUMEditor(1);
            }
            //连载联动
            $this.dom.columnDom.select2().on('change', function () {
                $this.dom.stagesDom.prop('checked', false).attr('disabled', false);
                $this.funObj().columnChange($(this).val(), $this.params.learnstages);
            });
            if (!$this.params.id) {
                $this.dom.columnDom.trigger('change');
            }
            //选中封面自动上传
            $('#cover_img').on('change', function () {
                $this.funObj().rebindUploadCover();
            });
            //点击保存/发布按钮
            $('#save, #publish').on('click', function(){
                $this.funObj().saveArticle($(this));
            });
        },
        funObj: function () {
            var $this = this;
            return {
                createUMEditor: function (type) {
                    var umOptions = {
                        autoHeightEnabled: false,
                        imageUrl: baseUrl + 'Read/uploadArticleImage',
                        imagePath: '',
                        //initialContent: '请输入文章内容...',
                        //autoClearinitialContent: true,
                        textarea: 'contents',
                        imageScaleEnabled: false,
                        dropFileEnabled: true
                    };
                    umOptions.toolbar = $this.params.toolbarConfig[type];
                    UM.getEditor('contents', umOptions);
                },
                // 实例化编辑器
                createUEditor: function () {
                    $this.params.ueOption.toolbars = $this.params.toolbarConfig;
                    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                    UE.Editor.prototype.getActionUrl = function(action) {
                        if (action == 'uploadimage') {
                            return '/Read/uploadArticleImage';
                        } else {
                            return this._bkGetActionUrl.call(this, action);
                        }
                    };
                    $this.params.ue = UE.getEditor('contents', $this.params.ueOption);
                },

                // 连载联动
                columnChange: function (columnsId, existLearnStages) {
                    xhExtra.ajaxRequest('Read/getChannelChild', {id: columnsId}, {}, function (data) {
                        $this.dom.markerDom.find('option').remove();//.append('<option></option>');
                        $this.dom.markerDom.select2({placeholder: '选择连载', data: data.marker});
                        if (existLearnStages) {//编辑文章初次进来
                            var learnStages = existLearnStages.split(',');
                            var allLearnStages = data.stages.split(',');
                            $.each(learnStages, function (index, stage) {
                                $this.dom.stagesDom.eq(stage - 1).prop('checked', true);
                            });
                            $this.dom.stagesDom.each(function () {
                                var inArr = $.inArray($(this).val(), allLearnStages);
                                if (inArr < 0) {
                                    $(this).prop('disabled', true);
                                }
                            });
                        } else {//栏目变动
                            //利用索引选中相应学段
                            var learnStages = data.stages.split(',');
                            $.each(learnStages, function (index, stage) {
                                $this.dom.stagesDom.eq(stage - 1).prop('checked', true);
                            });
                            //遍历未选中学段并禁用
                            $this.dom.stagesDom.each(function () {
                                if (!$(this).prop('checked')) {
                                    $(this).prop('disabled', true);
                                }
                            });
                        }

                        if ($this.params.markerId) {
                            $this.dom.markerDom.val($this.params.markerId).trigger('change');
                        }
                    });
                },

                // 选中封面自动上传
                rebindUploadCover: function () {
                    var coverImgDom = $('#cover_img');
                    $this.dom.coverUrlDom.val('').attr('placeholder', '上传中，请稍后...');
                    $.ajaxFileUpload({
                        url: baseUrl + 'Read/uploadArticleImage',
                        secureuri: false,
                        fileElementId: coverImgDom[0].id,                               //file标签的id  
                        dataType: 'json',                                               //返回数据的类型  
                        success: function (data, status) {
                            if (data.error) {
                                window.top.xhTop.showMessage({
                                    title: data.error,
                                    type: 'error'
                                });
                                return false;
                            }
                            $this.dom.coverUrlDom.val(data.url);
                        },
                        error: function (data, status, e) {
                            window.top.xhTop.showMessage({
                                title: e,
                                type: 'error'
                            });
                            $this.funObj().rebindUploadCover();
                        }
                    });
                },

                //点击保存/发布按钮
                saveArticle: function (btnDom) {
                    $this.dom.columnDom.add($this.dom.markerDom).add($this.dom.typeDom).prop("disabled", false);
                    var title = $('#title').val();
                    if (!title) {
                        window.top.xhTop.showMessage({
                            title: '文章标题不能为空！',
                            type: 'error'
                        });
                        return false;
                    }
                    if (title.length > 38) {
                        window.top.xhTop.showMessage({
                            title: '文章标题超出长度！',
                            type: 'error'
                        });
                        return false;
                    }
                    if ($(":checkbox[name*=learnstages]:checked").length <= 0) {
                        window.top.xhTop.showMessage({
                            title: '年段不能为空！',
                            type: 'error'
                        });
                        return false;
                    }
                    var releaseStatus = btnDom.attr('releasestatus');
                    // 判断当前点击的是否为立即发布
                    if (releaseStatus == 1 && $this.params.release == false) {
                        window.top.swal({
                            title: '是否确认立即发布？',
                            type: 'question',
                            showCancelButton: true,
                            showCloseButton:true,
                            confirmButtonColor: '#3085d6',
                            cancelButtonColor: '#d33',
                            confirmButtonText: '立即发布'
                        }).then(function(isConfirm) {
                            if (isConfirm) {
                                $this.funObj().saveArticleWithStatus(releaseStatus);
                            }
                        }, function(dismiss) {});
                    } else {
                        $this.funObj().saveArticleWithStatus(releaseStatus);
                    }
                },

                // 提交保存文章
                saveArticleWithStatus: function (releaseStatus) {
                    //提交表单，并提交 文章发布状态
                    $this.form.submit('Read/modifyArticleData',{releasestatus: releaseStatus},function (res) {
                        if (xhExtra.checkError(res)) {
                            return false;
                        }
                        window.top.xhTop.showSuccess(res.msg);
                        if ($this.params.release) {
                            $this.dom.columnDom.add($this.dom.markerDom).add($this.dom.typeDom).prop("disabled", true);
                        }
                        var manageFrame = window.top.xhTop.getFrameByName('文章管理');
                        if (manageFrame) {
                            manageFrame.obj.dataGrid.reload();
                        }
                        window.top.xhTop.closeActiveTab();
                    },{check:false});
                }
            }
        }
    }
};


// /**
//  * Created by CK on 2017/3/7.
//  */
// $(document).ready(function(){
//     var id = xhTool.getQuery('id'),
//         $form = new xhForm($('#form_article')),
//         columnDom = $('#columns'),
//         markerDom = $('#marker'),
//         stagesDom = $(':checkbox[name*=learnstages]'),
//         typeDom   = $('#articletype'),
//         markerId,
//         um,
//         release = false,
//         umOptions = {
//             autoHeightEnabled: false,
//             imageUrl: baseUrl + 'Read/uploadArticleImage',
//             imagePath : '',
//             //initialContent: '请输入文章内容...',
//             //autoClearinitialContent: true,
//             textarea: 'contents',
//             imageScaleEnabled: false,
//             dropFileEnabled: true
//         };
//     var toolbarConfig = {
//         '1': [
//             'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat',
//             '| insertorderedlist insertunorderedlist | selectall cleardoc paragraph' ,
//             '| justifyleft justifycenter justifyright ',
//             '| image',
//             '| horizontal preview ',
//             '| formula',
//             '| formula1 formula2 formula3 formula4 formula5 formula6 formula7 formula8 formula9 formula10 formula11 formula12 formula13 formula14'
//         ],
//         '2': [
//             'source | undo redo ',
//             '| selectall cleardoc' ,
//             '| image',
//             '| formula',
//             '| formula1 formula2 formula3 formula4 formula5 formula6 formula7 formula8 formula9 formula10 formula11 formula12 formula13 formula14'
//         ]
//     };
//
//     if(id){
//         $.post(baseUrl + 'Read/getArticleInfo', {id: id}, function(info){
//             // $('#form_article').xhForm('fillData', info);
//             $form.fill(info);
//             markerId = info.marker;
//             columnDom.trigger('change');
//             createUMEditor(typeDom.val());
//             if(info.releasestatus == 1){
//                 release = true;
//                 $('#save').fadeOut();
//                 $('#title').attr('readonly', true);
//                 columnDom.add(markerDom).add(typeDom).prop("disabled", true);
//             }
//         }, 'json');
//     }
//     //实例化编辑器
//     if(!id){
//         createUMEditor('1');
//     }
//     typeDom.on('change', function(){
//         var content = um.getContent();
//         um.destroy();
//         umOptions.autoClearinitialContent = false;
//         $('#contents').wrap("<div></div>").val(content);
//         createUMEditor($(this).val());
//     });
//
//     //连载联动
//     columnDom.select2().on('change', function(){
//         stagesDom.prop('checked', false).attr('disabled', false);
//         $.post(baseUrl + 'Read/getChannelChild', {id: $(this).val()}, function(data){
//             markerDom.find('option').remove();//.append('<option></option>');
//             markerDom.select2({placeholder: '选择连载', data: data.marker});
//             //利用索引选中相应学段
//             var learnStages = data.stages.split(',');
//             $.each(learnStages, function(index, stage){
//                 stagesDom.eq(stage - 1).prop('checked', true);
//             });
//             //遍历未选中学段并禁用
//             stagesDom.each(function(){
//                 //var $this = $(this);
//                 if(!$(this).prop('checked')){
//                     $(this).prop('disabled', true);
//                 }
//             });
//             if(markerId){
//                 markerDom.val(markerId).trigger('change');
//             }
//         }, 'json');
//     });
//     if(!id){
//         columnDom.trigger('change');
//     }
//
//     //选中封面自动上传
//     var coverUrlDom = $('#coverurl');
//     rebindUploadCover();
//     function rebindUploadCover()
//     {
//         var coverImgDom = $('#cover_img');
//         coverImgDom.on('change', function(){
//             coverUrlDom.val('').attr('placeholder', '上传中，请稍后...');
//             $.ajaxFileUpload({
//                 url: baseUrl + 'Read/uploadArticleImage',
//                 secureuri:false,
//                 fileElementId: coverImgDom[0].id,                               //file标签的id  
//                 dataType: 'json',                                               //返回数据的类型  
//                 success: function (data, status) {
//                     if(data.error) {
//                         window.top.xhTop.showMessage({
//                             title: data.error,
//                             type: 'error'
//                         });
//                         return false;
//                     }
//                     coverUrlDom.val(data.url);
//                     rebindUploadCover();
//                 },
//                 error: function (data, status, e) {
//                     window.top.xhTop.showMessage({
//                         title: e,
//                         type: 'error'
//                     });
//                     rebindUploadCover();
//                 }
//             });
//         });
//     }
//     //点击保存/发布按钮
//     $('#save, #publish').on('click', function(){
//         columnDom.add(markerDom).add(typeDom).prop("disabled", false);
//         var title = $('#title').val();
//         if(!title){
//             window.top.xhTop.showMessage({
//                 title: '文章标题不能为空！',
//                 type: 'error'
//             });
//             return false;
//         }
//         if(title.length > 38){
//             window.top.xhTop.showMessage({
//                 title: '文章标题超出长度！',
//                 type: 'error'
//             });
//             return false;
//         }
//         if($(":checkbox[name*=learnstages]:checked").length <= 0){
//             window.top.xhTop.showMessage({
//                 title: '年段不能为空！',
//                 type: 'error'
//             });
//             return false;
//         }
//         var btnDom = $(this);
//         var releaseStatus = $(this).attr('releasestatus');
//         if(releaseStatus == 1 && release == false){
//             window.top.swal({
//                 title: '是否确认立即发布？',
//                 type: 'question',
//                 showCancelButton: true,
//                 showCloseButton:true,
//                 confirmButtonColor: '#3085d6',
//                 cancelButtonColor: '#d33',
//                 confirmButtonText: '立即发布'
//             }).then(function(isConfirm) {
//                 if (isConfirm) {
//                     saveArticleWithStatus(btnDom, releaseStatus);
//                 }
//             }, function(dismiss) {});
//         }
//         else{
//             saveArticleWithStatus(btnDom, releaseStatus);
//         }
//     });
//
//     /**
//      * 提交表单保存文章
//      *
//      * @param btnDom
//      * @param releaseStatus
//      *
//      * create by ck 20170321
//      */
//     function saveArticleWithStatus(btnDom, releaseStatus){
//         //添加图标，禁用自身及兄弟按钮
//         btnDom.append(' <i class="fa fa-spinner fa-spin"></i>').attr('disabled', true).siblings('a').attr('disabled', true);
//         //提交表单，并提交 文章发布状态
//         $('#form_article').ajaxSubmit({
//             data: {releasestatus: releaseStatus},
//             success: function(result){
//                 if(result.indexOf('success') >= 0){
//                     result = result.replace('success:', '');
//                     window.top.xhTop.showMessage({
//                         title: '保存成功！',
//                         text: result,
//                         type: 'success'
//                     });
//                     var manageFrame = window.top.xhTop.getFrameByName('文章管理');
//                     if(manageFrame){
//                         manageFrame.list.dataGridReload();
//                     }
//                     window.top.xhTop.closeActiveTab();
//                     return false;
//                 }
//                 btnDom.text(btnDom.text()).attr('disabled', false).siblings('a').attr('disabled', false);
//                 window.top.xhTop.showMessage({
//                     title: result,
//                     type: 'error'
//                 });
//                 if(release){
//                     columnDom.add(markerDom).add(typeDom).prop("disabled", true);
//                 }
//             },
//             error: function(state, result){
//                 window.top.xhTop.showMessage({
//                     title: result,
//                     type: 'error'
//                 });
//                 btnDom.text(btnDom.text()).attr('disabled', false).siblings('a').attr('disabled', false);
//                 if(release){
//                     columnDom.add(markerDom).add(typeDom).prop("disabled", true);
//                 }
//             }
//             //timeout:3000
//         });
//     }
//
//     function createUMEditor(type) {
//         umOptions.toolbar = toolbarConfig[type];
//         um = UM.getEditor('contents', umOptions);
//     }
// });
